//
//  AppDelegate.swift
//  SinaWeiBo20
//
//  Created by tarena on 16/3/17.
//  Copyright © 2016年 tarena. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        //实例化窗口及其根视图控制器
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.makeKeyAndVisible()
        
        //设置主题色
        setThemeColor()
        
        //注册通知
        registerNotification()
        
        //
        window?.rootViewController = defaultRootController()
        
        return true
    }
    
    
    private func setThemeColor() {
        UINavigationBar.appearance().tintColor = themeColor
        UITabBar.appearance().tintColor = themeColor
    }
    
    //监听通知
    private func registerNotification() {
        //观测某个对象发出的通知 如果为nil  就是观测所有的对象发出的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchToRootVC:", name: AppSwitchRootViewController, object: nil)
    }
    
    @objc private func switchToRootVC(notification : NSNotification) {
        print("notifi:\(notification.object)")
        //跳转到MainVC
        if (notification.object as? String) != nil {
            window?.rootViewController = WelcomeViewController()
            return
        }
        window?.rootViewController = MainViewController()
    }
    
    //编码规范  移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //判断用户是否登录
    private func defaultRootController() ->UIViewController {
        print("userLogin:\(UserAccountViewModel().userLogin)")
        if UserAccountViewModel().userLogin {
           return isNewVersion() ? NewFeatureViewController() : WelcomeViewController()
        }
        return MainViewController()
        
    }
    
    //检测是否是新版本
    private func isNewVersion() -> Bool {
        //1. 获取新版本
        let versionStr = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as? String
        let versionNum = Double(versionStr!)
        
        //2.获取 旧版本  一般存放在沙盒3
        let key = "sandBoxKey"
        let userdefaults = NSUserDefaults.standardUserDefaults()
        let lastVersion = userdefaults.doubleForKey(key)
        
        //3. 保存新版本
        userdefaults.setDouble(versionNum!, forKey: key)
        
        //4. 同步沙盒
        userdefaults.synchronize()
        
        //5. 比较新旧版本
        return versionNum! > lastVersion
    }

}

